package openrr;

import java.awt.Canvas;

import org.lwjgl.LWJGLException;
import org.lwjgl.Sys;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import org.lwjgl.opengl.GL11;

import static org.lwjgl.util.glu.GLU.*;

import static org.lwjgl.opengl.GL11.*;
import openrr.Renderer;
import openrr.map.MapManager;

public class GameMain {
	public boolean running = false;
	
	public float mapX = 0.0f;
	public float mapY = 0.0f;
	public float mapPitch = 0.0f;
	public float mapRotation = 0.0f;
	public float mapZoomLevel = 400.0f;
	public float rotationFactor = 5.0f;
	
	public Renderer renderer;
	public Input inputHandler;
	public DisplayManager displayManager;
	public MapManager mapManager;
	
	public String separator = System.getProperty("file.separator");
	
	
	public boolean initialize(int width, int height) {
		try {
			
			
			// get available modes, and print out
			DisplayMode[] located_modes = Display.getAvailableDisplayModes();
			System.out.println("Found " + located_modes.length + " display modes");
			
			//Canvas canvas = new Canvas();
			
			
			Display.setLocation(100, 100);
			Display.setTitle("Open Rock Raiders - Delta");
			Display.setDisplayMode(new DisplayMode(width, height));
			//Display.setParent(canvas);
			Display.create();
			
			//openGL setup
			glViewport(0, 0, width, height);
			glMatrixMode(GL_PROJECTION);
			glLoadIdentity();
			gluPerspective(60.0f, (float)(width/height), 0.1f, 10000.0f);
			glMatrixMode(GL_MODELVIEW);
			glClearColor(94.0f/255.0f, 161.0f/255.0f, 255.0f/255.0f, 0.5f);
			glClearDepth(1.0);
			glShadeModel(GL_FLAT);
			glEnable(GL_DEPTH_TEST);
			glDepthFunc(GL_LEQUAL);
			glEnable(GL11.GL_CULL_FACE); 
			glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
			glEnable(GL_BLEND);
			glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
			
			displayManager = new DisplayManager(this);
			renderer = new openrr.Renderer(width, height, this);
			inputHandler = new Input(this);
			mapManager = new MapManager(this);
			return true;
		} catch (LWJGLException le) {
			le.printStackTrace();
		}
		return false;
	}
	
	public void mainLoop()
	{
		running = true;

		// wait for user to close window
		while (!Display.isCloseRequested() && running) {

			// handle input accordingly
			inputHandler.handleMouse();
			inputHandler.handleKeyboard();

			// render something
			renderer.render();

			// update display as needed
			Display.update();

			// no need to run at full speed
			try {
				Thread.sleep(1000/60);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	public static void sleep(long duration) {
		try {
		    Thread.sleep((duration * Sys.getTimerResolution()) / 1000);
		} catch (InterruptedException inte) {}
	}
}
